package com.li.springbootproject.service.rabbitmq;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.li.springbootproject.config.rabbitmq.RabbitMqConst;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 8/24/2022 8:50 AM
 */
@Component
public class RabbitMqDequeThreeConsume {

    private static final Logger logger = LoggerFactory.getLogger(RabbitMqDequeThreeConsume.class);

    /**
     * basicAck模式：表示成功确认，使用此回执方法后，消息会被rabbitmq broker删除。
     * basicNack模式：表示失败确认，一般在消费消息异常时用到此方法，可以将消息重新投递入队列。
     * basicReject模式：拒绝消息，与basicNack区别在于不能进行批量操作，其他用法很相似。
     *
     * @param message 消息
     * @param channel 通道
     */
    @RabbitListener(queues = RabbitMqConst.DEQUE_THREE)
    @RabbitHandler
    public void dequeThreeConsumeOne(Message message, Channel channel) {
        String messageId = message.getMessageProperties().getMessageId();
        System.out.println("message 消息编号：" + messageId);
        String str = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.println("message 消息体：" + str);
        //消息人工确认
        try {
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            channel.basicNack(deliveryTag, true, false);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
